package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
)

////  ip2long,  long2ip 转换测试

////////////// ip2long 底层实现原理 //////////////
func ip2long(ip net.IP) uint32 {
	a := uint32(ip[12])
	b := uint32(ip[13])
	c := uint32(ip[14])
	d := uint32(ip[15])
	fmt.Println(a, b, c, d)

	return uint32(a<<24 | b<<16 | c<<8 | d)
}
func long2ip(ip uint32) net.IP {
	a := byte((ip >> 24) & 0xFF)
	b := byte((ip >> 16) & 0xFF)
	c := byte((ip >> 8) & 0xFF)
	d := byte(ip & 0xFF)
	return net.IPv4(a, b, c, d)
}
func iptest() {
	var m = map[string]uint32{
		"217.171.224.66":  3651919938,
		"80.101.64.8":     1348812808,
		"188.204.155.170": 3167525802,
		"74.86.158.107":   1247190635,
		"83.83.140.49":    1397984305,
		"195.73.215.250":  3276396538,
		"37.74.94.85":     625630805,
		"62.195.45.68":    1052978500,
		"82.169.113.78":   1386836302,
		"145.53.147.68":   2436207428,
	}
	for k, v := range m {
		ip := net.ParseIP(k)
		if ip == nil {
			fmt.Println("parseip fail:", k, v)
			continue
		}
		if r := ip2long(ip); r != v {
			fmt.Println("ip2long fail:", r, v)
		}
		if r := long2ip(v).String(); r != k {
			fmt.Println("long2ip fail:", r, v)
		}
	}
}

// 利用 golang工具快速生成
func ip2long2(ip net.IP) uint32 {
	var long uint32
	binary.Read(bytes.NewBuffer(ip.To4()), binary.BigEndian, &long)
	return long
}
func main() {
	iptest()
}
